//
//  HLSpeakerView.m
//  YueYue
//
//  Created by hulu001 on 2023/6/13.
//

#import "HLSpeakerView.h"
#import <FrameAccessor/FrameAccessor.h>
#import <iflyMSC/iflyMSC.h>

@interface HLSpeakerView ()<IFlySpeechSynthesizerDelegate>
@property (strong,  nonatomic) UITextView *textLabel;
@property (strong,  nonatomic) UIButton *ChinesePlayBtn;
@property (strong,  nonatomic) UIButton *VietnamesePlayBtn;
@property (strong,  nonatomic) UIButton *EnglishPlayBtn;
@property (strong,  nonatomic) UIView *line;
@property (weak,    nonatomic) UIView *maskView;
@property (strong,  nonatomic) IFlySpeechSynthesizer *iFlySpeechSynthesizer;

@end

@implementation HLSpeakerView

- (void)dealloc
{
    NSLog(@"%s , %s", __FILE__, __func__);
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0];
        self.userInteractionEnabled = YES;
        
        self.textLabel = [UITextView.alloc init];
        self.textLabel.textColor = UIColor.whiteColor;
        self.textLabel.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0];
        self.textLabel.font = [UIFont systemFontOfSize:16];
        self.textLabel.editable = NO;
        [self addSubview:self.textLabel];
        
        self.line = [UIView.alloc initWithFrame:CGRectMake(0, 0, 268, 0.5)];
        self.line.backgroundColor = [UIColor colorWithRed:240/255.0 green:242/255.0 blue:245/255.0 alpha:0.1];
        [self addSubview:self.line];
        
        CGFloat btnWidth = (UIScreen.mainScreen.bounds.size.width - 80) / 3.f;
        
        self.ChinesePlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.ChinesePlayBtn.bounds = CGRectMake(0, 0, btnWidth, 44);
        self.ChinesePlayBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        self.ChinesePlayBtn.titleLabel.adjustsFontForContentSizeCategory = YES;
        self.ChinesePlayBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        [self.ChinesePlayBtn setTitle:@"读中文" forState:UIControlStateNormal];
        [self.ChinesePlayBtn setTitleColor:[UIColor.whiteColor colorWithAlphaComponent:0.2] forState:UIControlStateNormal];
        [self.ChinesePlayBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        [self.ChinesePlayBtn addTarget:self action:@selector(repeatPlay:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.ChinesePlayBtn];
        
        self.VietnamesePlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.VietnamesePlayBtn.bounds = CGRectMake(0, 0, btnWidth, 44);
        self.VietnamesePlayBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.VietnamesePlayBtn setTitle:@"读越南文" forState:UIControlStateNormal];
        [self.VietnamesePlayBtn setTitleColor:[UIColor.whiteColor colorWithAlphaComponent:0.2] forState:UIControlStateNormal];
        [self.VietnamesePlayBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        [self.VietnamesePlayBtn addTarget:self action:@selector(repeatPlay:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.VietnamesePlayBtn];
        
        self.EnglishPlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.EnglishPlayBtn.bounds = CGRectMake(0, 0, btnWidth, 44);
        self.EnglishPlayBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.EnglishPlayBtn setTitle:@"读英文" forState:UIControlStateNormal];
        [self.EnglishPlayBtn setTitleColor:[UIColor.whiteColor colorWithAlphaComponent:0.2] forState:UIControlStateNormal];
        [self.EnglishPlayBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        [self.EnglishPlayBtn addTarget:self action:@selector(repeatPlay:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.EnglishPlayBtn];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.textLabel.viewSize = CGSizeMake(UIScreen.mainScreen.bounds.size.width - 80 - 48, CGRectGetHeight(self.frame) - 24 - 24 - 44);
    self.textLabel.top = 24;
    self.textLabel.centerX = self.middleX;
    
    self.line.centerX = self.middleX;
    self.line.bottom = self.height - 44;
    
    self.ChinesePlayBtn.left = 0;
    self.ChinesePlayBtn.bottom = self.height;
    
    self.VietnamesePlayBtn.centerX = self.middleX;
    self.VietnamesePlayBtn.bottom = self.height;
    
    self.EnglishPlayBtn.right = self.width;
    self.EnglishPlayBtn.bottom = self.height;
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 1.5);
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0].CGColor);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10];
    CGContextAddPath(context, bezierPath.CGPath);
    CGContextFillPath(context);
    
//    self.layer.shadowColor = [UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0].CGColor;
//    self.layer.shadowOpacity = 1.0;
//    self.layer.shadowOffset = CGSizeMake(0.0f, 2.0f);
//    self.layer.shadowRadius = 4;
}

- (CGSize)sizeThatFits:(CGSize)size
{
    // 固定宽度268px
//    CGFloat textHeight = [self.textLabel.text?:@"请重新长按消息进行朗读" boundingRectWithSize:CGSizeMake(UIScreen.mainScreen.bounds.size.width - 80 - 48, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.textLabel.font} context:nil].size.height + 10;
    CGFloat textHeight = [self.textLabel sizeThatFits:CGSizeMake(UIScreen.mainScreen.bounds.size.width - 80 - 48, MAXFLOAT)].height;
    CGFloat height = 24 + textHeight + 24 + 44;
    if (height > UIScreen.mainScreen.bounds.size.height - 100) {
        self.textLabel.scrollEnabled = YES;
        height = UIScreen.mainScreen.bounds.size.height - 100;
    } else {
        self.textLabel.scrollEnabled = NO;
    }
    
    return CGSizeMake(UIScreen.mainScreen.bounds.size.width - 80, height);
}

- (void)setSpeakContent:(NSString *)speakContent
{
    _speakContent = speakContent;
    self.textLabel.text = speakContent;
}

- (void)show
{
    /*
     * 讯飞
     */
    //获取语音合成单例
    _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    //设置协议委托对象
    _iFlySpeechSynthesizer.delegate = self;
    //设置合成参数
    //设置在线工作方式
    [_iFlySpeechSynthesizer setParameter:[IFlySpeechConstant TYPE_CLOUD]
     forKey:[IFlySpeechConstant ENGINE_TYPE]];
    //设置音量，取值范围 0~100
    [_iFlySpeechSynthesizer setParameter:@"50"
    forKey: [IFlySpeechConstant VOLUME]];
    //保存合成文件名，如不再需要，设置为nil或者为空表示取消，默认目录位于library/cache下
    [_iFlySpeechSynthesizer setParameter:@"tts.pcm"
     forKey: [IFlySpeechConstant TTS_AUDIO_PATH]];
    [_iFlySpeechSynthesizer setParameter:@"unicode" forKey:[IFlySpeechConstant TEXT_ENCODING]];
    
    [self sizeToFit];
    
    // 加载到主window
    UIView *maskView = [UIView.alloc initWithFrame:UIScreen.mainScreen.bounds];
    maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
    self.maskView = maskView;
    [self.maskView addSubview:self];
    [self.maskView addGestureRecognizer:[UITapGestureRecognizer.alloc initWithTarget:self action:@selector(tap:)]];
    
    UIView *onView = UIApplication.sharedApplication.delegate.window;
    [onView addSubview:maskView];
    
    // 设置初始状态
    self.center = self.maskView.middlePoint; // 显示在屏幕中间
    self.transform = CGAffineTransformMakeScale(0.2, 0.2); // 初始缩放大小
    self.alpha = 0.2; // 初始透明度
    
    // 动画
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.transform = CGAffineTransformIdentity;
        self.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}

#pragma mark - <action>

- (void)tap:(UITapGestureRecognizer *)ges
{
    CGPoint point = [ges locationInView:self];
    if ([self pointInside:point withEvent:nil]) {
        return;
    }
    
    if (_iFlySpeechSynthesizer.isSpeaking) {
        [_iFlySpeechSynthesizer stopSpeaking];
        [IFlySpeechSynthesizer destroy];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        self.transform = CGAffineTransformMakeScale(0.2, 0.2); // 初始缩放大小
        self.alpha = 0.2; // 初始透明度
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.maskView removeFromSuperview];
    }];
}

- (void)repeatPlay:(UIButton *)btn
{
    if (btn.selected) {
        return;
    }
    if (_iFlySpeechSynthesizer.isSpeaking) {
        [_iFlySpeechSynthesizer stopSpeaking];
    }
    
    btn.selected = YES;
    
    if (btn == self.ChinesePlayBtn) {
        [_iFlySpeechSynthesizer setParameter:@"x2_xiaoxue"
         forKey: [IFlySpeechConstant VOICE_NAME]];
        
        self.VietnamesePlayBtn.selected = NO;
        self.EnglishPlayBtn.selected = NO;
    } else if (btn == self.VietnamesePlayBtn) {
        [_iFlySpeechSynthesizer setParameter:@"xiaoyun"
         forKey: [IFlySpeechConstant VOICE_NAME]];
        
        self.ChinesePlayBtn.selected = NO;
        self.EnglishPlayBtn.selected = NO;
    } else {
        [_iFlySpeechSynthesizer setParameter:@"x2_catherine"
         forKey: [IFlySpeechConstant VOICE_NAME]];
        
        self.ChinesePlayBtn.selected = NO;
        self.VietnamesePlayBtn.selected = NO;
    }
    
    [self->_iFlySpeechSynthesizer startSpeaking:self.textLabel.text];
}

//合成结束
- (void) onCompleted:(IFlySpeechError *) error {
    if (error.errorCode != 0) {
        [QMUITips showError:error.errorDesc];
    }
}
//合成开始
- (void) onSpeakBegin {
    NSLog(@"合成开始");
}
//合成缓冲进度
- (void) onBufferProgress:(int) progress message:(NSString *)msg {
    
}
//合成播放进度
- (void) onSpeakProgress:(int) progress beginPos:(int)beginPos endPos:(int)endPos {
    
    // endpos可能会导致越界 与文本不匹配
//    self.textLabel.attributedText = ({
//        NSMutableAttributedString *attributed = [NSMutableAttributedString.alloc initWithString:_speakContent attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0]}];
//        [attributed addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor colorWithRed:148/255.0 green:106/255.0 blue:250/255.0 alpha:1.0]} range:NSMakeRange(0, endPos/2)];
//
//        attributed;
//    });
    
    if (progress == 100) {
        self.ChinesePlayBtn.selected = NO;
        self.VietnamesePlayBtn.selected = NO;
        self.EnglishPlayBtn.selected = NO;
    }
}


@end
